import math

import threading
import time

from pynput.keyboard import Key
from pynput.mouse import Listener
from pytesseract import pytesseract
from PIL import Image
import pyautogui


# 构建坐标点对象，包含构造函数知识点
class Pos:
    x = 0;
    y = 0;
    gongsu = 0;

    # 构造函数
    def __init__(self, x, y):
        self.x = x;
        self.y = y;


# 读取内存地址获取数值（十进制），包含--------内存读取,字符串分割，数组反转，进制转换知识点
def readMemory(dm, hwnd, adr, dataType):
    print('窗口句柄----', hwnd);
    # 多重基址读写，具体看大漠官方文档
    # dataType-----0读整型，1读浮点型
    if dataType == 0:
        a = dm.ReadInt(hwnd, adr, 0);
    if dataType == 1:
        a = dm.ReadFloat(hwnd, adr);
    print("读取到的值是----", a)
    return a;


# 写入内存
def writeData(dm, hwnd, adr, dataType, data):
    # dataType----0写整型，1写浮点型
    if dataType == 0:
        dm_ret = dm.WriteInt(hwnd, adr, 0, data);
    if dataType == 1:
        dm_ret = dm.WriteFloat(hwnd, adr, data);
    print(('写入成功', data) if (dm_ret == 1) else '写入失败');


# 计算两点坐标距离包含计算两点坐标知识点
def pathAbs(x1, y1, x2, y2):
    result = math.sqrt(
        math.pow(
            x1 -
            x2,
            2) +
        math.pow(
            y1 -
            y2,
            2))
    print(x1, ',', y1, '与', x2, ',', y2, '之间的距离为：', result)
    return result


# 获取攻速,包含------截屏函数知识点
def getGongSuPic():
    # 截屏函数
    img = pyautogui.screenshot(region=[487, 1024, 528 - 487, 1046 - 1024])  # x,y,w,h
    img.save('gongsu.bmp')
    print('攻速截屏完成')


# 不断的获取攻速，包含---ocr识别，try，catch，字符串转浮点型知识点
def getLegendAttackSpeed():
    while 1:
        time.sleep(2);
        getGongSuPic();
        # ocr识别技术，从图片读取文本出来
        text = pytesseract.image_to_string(Image.open('gongsu.bmp'), lang='eng')
        try:
            # 字符串转浮点型
            Pos.gongsu = float(text);
            print('识别出', Pos.gongsu)
        except:
            print('识别错误')


# 计算敌人/自己位置并返回,是个（500,600），（500,600）型的数组，没有返回0
# 包含-----字符串分割数组api，集合push操作，时间戳api,及大漠找图api的知识点
def posByPic(str, x1, y1, x2, y2, dm):
    enemy = [];
    # 当前时间戳
    start = time.time()
    a = dm_ret = dm.FindPicEx(x1, y1, x2, y2, str, "000000", 0.9, 1)
    if a == '':
        return 0;
    print(a);
    # 分割为字符数组：（0,500,600），（0,500,600）
    poss = a.split("|")
    for s in poss:
        pos = s.split(",")
        enemy.append(Pos((int)(pos[1]), (int)(pos[2])));
    # 当前时间戳
    end = time.time();
    print('花费时间共', end - start)
    return enemy;


# 绑定窗口，包含-----获取窗口句柄，激活窗口，后台绑定窗口（不一定所有游戏支持后台）知识点
def toBindWindow(dm):
    # 绑定窗口
    hwnd = dm.FindWindow("扫雷", "扫雷")
    print('激活窗口情况', dm.SetWindowState(hwnd, 1));
    # 后台绑定窗口，具体看大漠文档
    isBind = dm.BindWindow(hwnd, "normal", "dx", "normal", 0)
    print(dm.GetLastError())
    print('窗口绑定效果', isBind);
    isMoved = dm.MoveTo(279, 264);
    print('鼠标已移动', isMoved);
    time.sleep(1)
    isClicked = dm.LeftClick()
    print('左键已点击', isClicked)


#  鼠标监听函数，包含---------开启线程知识点
def listenmouse():
    while 1:
        with Listener(on_click=on_click) as listener:
            listener.join()
            # 开启线程，执行readMemory函数中的代码
        threading.Thread(target=readMemory).start()


# 键盘监控函数
def listenKet():
    while 1:
        with Listener(on_press=on_press, on_release=on_release) as listener:
            listener.join()


# 鼠标点击执行的时间
def on_click(x, y, button, pressed):
    if button.name == 'left' and not pressed:
        return False;


# 监控键盘，一旦监听到按下空格，就退出监听
def on_press(key):
    if key == Key.space:
        return False;


# 全局监控键盘，一旦监听到弹起某个按键，就执行相关过程，貌似之后只能执行一些打印相关的方法，
# 否则程序卡死
def on_release(key):
    #     global isLock;
    print('{0} released'.format(key))
